<?php

namespace haibao\tv\business\payment;

use \haibao\tv\business\BusinessException;

class TvUserOrder extends \haibao\tv\business\Base{
    
    /**
	 * @var $_instance
	 */
	private static $_instance;
	
	/**
	 * instance()
	 */
	private static function instance(){
		if(!self::$_instance){
			self::$_instance = new \haibao\tv\data\payment\TvUserOrder();
		}
		return self::$_instance;
	}
	
	public static function getOrderByOrderId($orderId){
	    return self::instance()->getOrderByOrderId($orderId);
	}

    public static function prepareOrder($userId, $productId){
        $data = new \haibao\user\data\User();
        $user = $data->getUserInfo($userId);
        if(!$user){
            throw new BusinessException('用户不存在');
        }
        
        $data = new \haibao\tv\data\payment\TvVipProduct();
        $product = $data->getProductByProductId($productId);
        if(!$product){
            throw new BusinessException('套餐不存在');
        }
        
        $model = new \haibao\tv\model\data\payment\TvUserOrder();
        $orderId = self::generateOrderId();
        $model->OrderId = $orderId;
        $model->UserId = $userId;
        $model->ProductPrice = $product['ProductPrice'];
        $model->ProductId = $product['ProductId'];
        $model->PayCard = '支付宝';
        $model->PayStatus = \haibao\tv\model\data\payment\TvUserOrder::PAY_STATUS_NOT;
        $model->PayTime = new \DateTime();
        self::instance()->saveOrder($model);
        
        return array($orderId, $product);
    }
    
    /**
     * 交易成功
     */
    public static function paySuccess($userId, $orderId){
        $order = self::getOrderByOrderId($orderId);
        $userVipId = null;
        if($order && $userId == $order['UserId'] && $order['PayStatus'] == \haibao\tv\model\data\payment\TvUserOrder::PAY_STATUS_NOT){
            $userVipId = self::instance()->paySuccess(intval($userId), $orderId);
        }
        return $userVipId;
    }
    
    /**
     * 从redis中查看支付结果是否成功
     */
    public static function getPaymentResult($userId, $orderId){
        return self::instance()->getPaymentResult($userId, $orderId);
    }
    
    /**
     * 生成订单Id
     */
    public static function generateOrderId(){
        $utimestamp = microtime(true);
        $timestamp = floor($utimestamp);
        $milliseconds = round(($utimestamp - $timestamp) * 1000000);
        $udate = date(preg_replace('`(?<!\\\\)u`', $milliseconds, 'u'), $timestamp);
        
        $data = new \haibao\tv\data\payment\TvUserOrder();
        return date('YmdHis').str_pad($udate, 6,'0').'TV'.$data->getUniqid();
    }

} 